﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Automatic audit fields | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Automatic audit fields | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.0.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="automatic-audit-fields">Automatic audit fields</h1>

<p>instead of setting the audit values manually on each and every save or update operation, you can take advantage of a <code>DBContext</code> instance where you will instantiate the context by providing it with the details of the current user performing the operations once, and then use the db context to perform all subsequesnt save/update operations so that all the audit fields will be set on the entities automatically.</p>
<h2 id="enable-audit-fields">Enable audit fields</h2>
<p>simply add a property of type <code>ModifiedBy</code> to the entity class where you'd like to enable audit fields. The <code>ModifiedBy</code> type is provided by the library. It can be inherited and other properties can be added to it as you please.</p>
<pre><code class="lang-csharp">public class Book : Entity
{
    public string Title { get; set; }
    public ModifiedBy ModifiedBy { get; set; }
}
</code></pre>
<h2 id="instantiate-a-dbcontext">Instantiate a DBContext</h2>
<p>instantiate a context by providing it a <code>ModifiedBy</code> instance with the current user's details filled in.</p>
<pre><code class="lang-csharp">var currentUser = new ModifiedBy
{
    UserID = &quot;xxxxxxxxxxxx&quot;,
    UserName = &quot;Kip Jennings&quot;
};

var db = new DBContext(modifiedBy: currentUser);
</code></pre>
<h2 id="perform-entity-operations">Perform entity operations</h2>
<p>in order for the auto audit fields to work, you must use the db context to perform the operations instead of the <code>DB</code> static methods like you'd typically use.</p>
<pre><code class="lang-csharp">var book = new Book { Title = &quot;test book&quot; };

await db.SaveAsync(book);

await db.Update&lt;Book&gt;()
        .MatchID(book.ID)
        .Modify(b =&gt; b.Title, &quot;updated title&quot;)
        .ExecuteAsync();
</code></pre>
<p>doing so will result in the following document in mongodb:</p>
<pre><code>{
	&quot;_id&quot; : ObjectId(&quot;xxxxxxxxxxxx&quot;),
	&quot;Title&quot; : &quot;updated title&quot;, //this will initially be 'test book'
	&quot;ModifiedBy&quot; : {
		&quot;UserID&quot; : &quot;xxxxxxxxxxxx&quot;,
		&quot;UserName&quot; : &quot;Kip Jennings&quot;
	}
}
</code></pre>
<h2 id="getset-audit-values">Get/set audit values</h2>
<p>it is also possible to instantiate a <code>DBContext</code> without supplying a <code>ModifiedBy</code> to the constructor and set or get it like so:</p>
<pre><code class="lang-csharp">var dbContext = new DBContext();

db.ModifiedBy = new ModifiedBy
{
    UserID = &quot;xxxxxxxxxxxx&quot;,
    UserName = &quot;Kip Jennings&quot;
};

var currentUser = db.ModifiedBy;
</code></pre>
<h2 id="transaction-support">Transaction support</h2>
<p>a transaction with audit field support can be performed with the DBContext like so:</p>
<pre><code class="lang-csharp">var db = new DBContext(modifiedBy: currentUser);

using (db.Transaction())
{
    await db.SaveAsync(book);
    await db.CommitAsync();
}
</code></pre>
<p>or it can be performed with a <code>Transaction</code> instance like so:</p>
<pre><code class="lang-csharp">using (var TN = DB.Transaction(modifiedBy: currentUser))
{
    await TN.SaveAsync(book);
    await TN.CommitAsync();
}
</code></pre>
<div class="NOTE">
<h5>Note</h5>
<p>please refer to the <a href="Transactions.html">transactions page</a> for a detailed explanation of how transactions work.</p>
</div>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
